package com.gem.taskplan.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.gem.taskplan.adapter.MemberListAdapter;
import com.gem.taskplan.service.BackAcitvity;
import com.gem.taskplan.service.CheckedNetWork;
import com.gem.taskplan.util.HttpUtil;
import com.gem.taskplan.util.PropertiesUtil;
import com.gem.taskplan.util.SysApplication;

import android.os.Bundle;
import android.R.bool;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MemberListActivity extends Activity {

	private SharedPreferences sharedPreferences;       //得到保存的信息
	private String curUserName = null;                 //当前登陆名
	private SwipeRefreshLayout refreshWorkTable = null;//下拉刷新
	private List<Map<String, String>> list = null;		//存放成员信息
	private ListView userListvView = null;				//存放成员的listview
	private ImageView backImageView = null;				//返回按钮图片
	private ImageView addMemberImageView = null;		//添加成员按钮图片
	private EditText editText = null;
	private EditText appendInfo = null;
	private View view;
	private MemberListAdapter memberListAdapter = null;
	private LayoutInflater inflater;
	private String url = "/SetServlet";
	private String url2 = "/ReceiveMessageServlet";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_member_list);
		
		/***********退出程序************/
		SysApplication.getInstance().addActivity(this);
		
		/************获得访问服务器的地址***************/
		url = PropertiesUtil.getServerURL(this)+url;
		url2 =  PropertiesUtil.getServerURL(this)+url2;
		
		/*******************************************/
		inflater = getLayoutInflater();
		view = inflater.inflate(R.layout.member_list, null);
		setContentView(R.layout.activity_member_list);
		backImageView = (ImageView)findViewById(R.id.backImage);
		refreshWorkTable = (SwipeRefreshLayout) findViewById(R.id.refreshMemberList);
		refreshWorkTable.setColorScheme(android.R.color.holo_red_light, android.R.color.holo_green_light,
				android.R.color.holo_blue_bright, android.R.color.holo_orange_light);//添加刷新颜色变化
		BackAcitvity.back(backImageView, MemberListActivity.this);
		userListvView = (ListView) findViewById(R.id.userList);
		addMemberImageView = (ImageView) findViewById(R.id.addMember);
		sharedPreferences = MemberListActivity.this.getSharedPreferences("taskPlanShare", Activity.MODE_PRIVATE);
		curUserName = sharedPreferences.getString("lastUser", "");
		//添加好友按钮监听时间
		addMemberImageView.setOnClickListener(new AddMemberImageSetOnClickListener());
		
		list = new ArrayList<Map<String,String>>();
		memberListAdapter = new MemberListAdapter(list, MemberListActivity.this, R.layout.member_list);
		inintData();
		userListvView.setAdapter(memberListAdapter);
		/***********************长按事件监听******************************/
		userListvView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				Toast.makeText(MemberListActivity.this, "nisdfaeferf",Toast.LENGTH_SHORT).show();
				
				if(CheckedNetWork.checkedConnection(MemberListActivity.this)){
//					if(true){
					final int position = arg2;
					final View view = arg1;
					final CheckBox checkBox = new CheckBox(MemberListActivity.this);
					checkBox.setText("是否将您从对方好友列表中移除！");
					new AlertDialog.Builder(MemberListActivity.this).setTitle("确定要移除该好友吗？")
					.setIcon(R.drawable.delete).setView(checkBox).setPositiveButton("确定",new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							TextView userName = (TextView) view.findViewById(R.id.memberName);
							/*********验证是否连接网络*************/
							if(!CheckedNetWork.checkedConnection(MemberListActivity.this)){
								return;
							}
							
							Map<String, String> map = new HashMap<String, String>();
							map.put("memberName",userName.getText().toString());
							map.put("action","deleteMemberRelation");
							map.put("curName",curUserName);
							if (checkBox.isChecked()) {
								map.put("choose", "yes");
							}else {
								map.put("choose", "no");
							}
							String result = null;
							try {
								result = HttpUtil.postRequest(url, map);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							System.out.println("MemberListActivity界面删除用户名的结果："+result);
							if (result.equals("yes")) {
								list.remove(position);
								memberListAdapter.notifyDataSetChanged();
								Toast.makeText(MemberListActivity.this, "删除成功！", Toast.LENGTH_SHORT).show();
							}else {
								Toast.makeText(MemberListActivity.this, "删除失败！", Toast.LENGTH_SHORT).show();
							}
						}
					}).setNegativeButton("取消",new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							
						}
					}).create().show();;
				}else {
					Toast.makeText(MemberListActivity.this, "您没有联网！",Toast.LENGTH_SHORT).show();
				}
				
				
				return false;
			}
		});
		refreshWorkTable.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				refreshWorkTable.setRefreshing(false);
				list.clear();
				inintData();
			}
		});
	}
	/***************************初始化数据*********************************/
	private void inintData(){
		//验证时否联网
		if(!CheckedNetWork.checkedConnection(this)){
			return;
		}
		
		System.out.println(curUserName);
		Map<String, String> map1 = new HashMap<String, String>();
		map1.put("user_name", curUserName);
		map1.put("action", "queryUser");
		String result = null;
		try {
			result = HttpUtil.postRequest(url, map1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("result = "+result);
		String[] string = new String[]{"user_picture","user_name","user_sex","user_email"};
		try {
			JSONObject object = new JSONObject(result);
			JSONArray array = object.getJSONArray("userListJson");
			System.out.println("*********"+array.length());
			for (int j = 0; j < array.length(); j++) {
				JSONObject object3 = array.getJSONObject(j);
				JSONArray array2 = object3.getJSONArray("userListJson"+j);
				System.out.println("*********"+array2.length());
				String url = array2.getJSONObject(0).getString(string[0]);
				String name = array2.getJSONObject(1).getString(string[1]);
				String sex = array2.getJSONObject(2).getString(string[2]);
				String email = array2.getJSONObject(3).getString(string[3]);
				Map<String , String> map = new HashMap<String, String>();
				if (url.length() == 0) {
					map.put("url","");
					System.out.println("####"+map.get("url"));
				}else {
					map.put("url",url);
					System.out.println("####"+map.get("url"));
				}
				map.put("name", name);
				System.out.println("####"+map.get("name"));
				if (sex.length()==0) {
					map.put("sex","无");
				}else {

					map.put("sex", sex);
				}
				if (email.length()==0) {
					map.put("email", "无");
				}else {
					map.put("email", email);
				}
				System.out.println("####"+map.get("sex"));
				System.out.println("####"+map.get("email"));
				list.add(map);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		//刷新数据
		memberListAdapter.notifyDataSetChanged();
	}
	/**************************添加好友监听事件*********************************/
	private class AddMemberImageSetOnClickListener implements OnClickListener{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			LayoutInflater inflater = LayoutInflater.from(MemberListActivity.this);
			view = inflater.inflate(R.layout.addmember_dialog, null);
			Button button = (Button) view.findViewById(R.id.addMemberDialogButton);
			editText = (EditText) view.findViewById(R.id.sendContent);
			appendInfo = (EditText) view.findViewById(R.id.appendInfo);
			editText.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					editText.setText("");
				}
			});
			appendInfo.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					appendInfo.setText("");
				}
			});
			final AlertDialog dialog = new AlertDialog.Builder(MemberListActivity.this)
			.setTitle("添加成员").setView(view).create();
			dialog.show();
			button.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					boolean flag = false;
					for (int i = 0; i < list.size(); i++) {
						String memberName = list.get(i).get("name");
						if (editText.getText().toString().equals(memberName)) {
							flag=true;
							break;
						}
					}
					if(flag){
						Toast.makeText(MemberListActivity.this,"该成员已经被添加，不能重复添加好友！",Toast.LENGTH_SHORT).show();
						return;
					}
					String member = editText.getText().toString();
					String msg = appendInfo.getText().toString();
					/*********判断是否联网***************/
					if(!CheckedNetWork.checkedConnection(MemberListActivity.this)){
						return;
					}
					Map<String, String> map = new HashMap<String, String>();
					map.put("memberName", member);
					map.put("curName", curUserName);
					map.put("action", "addMember");
					map.put("appendInfo", msg);
					String result = null;
					try {
						result = HttpUtil.postRequest(url2, map);
					} catch (Exception e) {
						e.printStackTrace();
					}
					System.out.println("MemberListActivity添加成员-------"+result);
					if (result.equals("yes")) {
						dialog.cancel();
						Toast.makeText(MemberListActivity.this, "消息已发送，等待对方回应！", Toast.LENGTH_SHORT).show();
					}else if (result.equals("no1")) {
						Toast.makeText(MemberListActivity.this, "不存在该用户！", Toast.LENGTH_SHORT).show();
					}else {
//						Toast.makeText(MemberListActivity.this, "网络异常！请重新添加！", Toast.LENGTH_SHORT).show();
					}
				
				}
			});
			/*.setPositiveButton("添加",new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					String member = editText.getText().toString();
					String msg = appendInfo.getText().toString();
					Map<String, String> map = new HashMap<String, String>();
					map.put("memberName", member);
					map.put("curName", curUserName);
					map.put("action", "addMember");
					map.put("appendInfo", msg);
					String result = null;
					try {
						result = HttpUtil.postRequest(url2, map);
					} catch (Exception e) {
						e.printStackTrace();
					}
					System.out.println("MemberListActivity添加成员-------"+result);
					if (result.equals("yes")) {
						Toast.makeText(MemberListActivity.this, "消息已发送，等待对方回应！", Toast.LENGTH_SHORT).show();
					}else if (result.equals("no1")) {
						Toast.makeText(MemberListActivity.this, "不存在该用户！", Toast.LENGTH_SHORT).show();
					}else {
//						Toast.makeText(MemberListActivity.this, "网络异常！请重新添加！", Toast.LENGTH_SHORT).show();
					}
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
				}
			}).create();
			dialog.show();*/
		
		}
	
	}
}
